/**
 * 主播查看礼物组件
 * page主播查看礼物组件
 */
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/live/giftBox.dart';
import 'package:qgchat/common/action/filter/index.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/giftModel.dart';
import 'package:qgchat/http/models/giftlistModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:cached_network_image/cached_network_image.dart';

class AnchorGiftBox extends StatelessWidget {
  AnchorGiftBox({this.token, this.vid, Key key}) : super(key: key);

  final String token;
  final int vid;
  final GiftBoxBloc bloc = GiftBoxBloc();

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: bloc,
      child: Container(
        width: w100(context),
        height: px(500),
        decoration: BoxDecoration(
          color: col("2b2849"),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(px(24)),
            topRight: Radius.circular(px(24)),
          ),
        ),
        child: Column(
          children: <Widget>[
            // 顶部按钮
            headBtnHandle(context),
            // 礼物轮播
            swiperHandle(context),
          ],
        ),
      ),
    );
  }

  // 顶部按钮
  Widget headBtnHandle(context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: px(30)),
            child: Text(
              "查看礼物",
              style: TextStyle(
                color: Colors.white,
                fontSize: px(28),
              ),
            ),
          ),
          Container(
            width: px(128),
            height: px(92),
            child: FlatButton(
              onPressed: () => Navigator.pop(context),
              padding: EdgeInsets.all(px(0)),
              child: Text(
                "取消",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(34),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 生成轮播
  Widget swiperHandle(context) {
    // 单个礼物
    Widget gift(GiftlistModel giftItem, int g, int i) {
      return StreamBuilder(
        stream: bloc.choiceStream,
        initialData: bloc.choice,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          return Container(
            width: px(172),
            height: px(172),
            padding: EdgeInsets.all(px(4)),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(px(7)),
              color: col("2b2849"),
            ),
            child: FlatButton(
              onPressed: () => bloc.choiceGift(g, i),
              padding: EdgeInsets.zero,
              child: Container(
                width: flex1,
                decoration: BoxDecoration(
                  color: col("2b2849"),
                  borderRadius: BorderRadius.circular(px(7)),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    // 礼物图
                    Container(
                      width: px(70),
                      height: px(70),
                      decoration: BoxDecoration(
                        color: col("f8f8f8"),
                        borderRadius: BorderRadius.circular(px(10)),
                      ),
                      child: Stack(
                        overflow: Overflow.visible,
                        alignment: Alignment.center,
                        children: <Widget>[
                          Container(
                            width: px(42),
                            height: px(42),
                            // padding: EdgeInsets.all(px(14)),
                            child: CachedNetworkImage(
                              imageUrl: "${giftItem.giftIcon}",
                              fit: BoxFit.cover,
                              errorWidget: (context, url, error) {
                                return Image.asset(
                                  "assets/images/icon/giftbg.png",
                                );
                              },
                            ),
                          ),
                          stateBuilder(context, 'global', (GlobalState global) {
                            int i = global.receivedGift
                                .indexWhere((item) => item.id == giftItem.id);
                            if (i >= 0) {
                              GiftModel gift = global.receivedGift[i];
                              return Positioned(
                                top: -px(18),
                                right: -px(18),
                                child: Container(
                                  height: px(36),
                                  padding:
                                      EdgeInsets.symmetric(horizontal: px(11)),
                                  decoration: BoxDecoration(
                                    color: col("ffb240"),
                                    borderRadius: BorderRadius.circular(px(18)),
                                  ),
                                  child: Text(
                                    "${Filter.maxToAdd(gift?.number ?? 0, 99)}",
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: px(26),
                                    ),
                                  ),
                                ),
                              );
                            } else {
                              return Container();
                            }
                          }),
                        ],
                      ),
                    ),
                    // 礼物名
                    Container(
                      margin: EdgeInsets.only(top: px(15)),
                      child: Text(
                        "${giftItem.giftName}",
                        style: TextStyle(
                          height: .95,
                          color: Colors.white,
                          fontSize: px(24),
                        ),
                      ),
                    ),
                    // 金币
                    Container(
                      margin: EdgeInsets.only(top: px(5)),
                      child: Text(
                        "${giftItem.giftGold}金币",
                        style: TextStyle(
                          height: .95,
                          color: col("9594a4"),
                          fontSize: px(20),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      );
    }

    return StreamBuilder(
      stream: bloc.giftStream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.hasData) {
          List<List<GiftlistModel>> list = snapshot.data;

          return Container(
            width: w100(context),
            height: px(390),
            padding: EdgeInsets.symmetric(horizontal: px(30)),
            child: Swiper(
              onTap: (int index) {},
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  padding: EdgeInsets.only(bottom: px(46)),
                  child: Wrap(
                    children: list[index].asMap().keys.map((int i) {
                      return gift(list[index][i], index, i);
                    }).toList(),
                  ),
                );
              },
              pagination: SwiperPagination(
                builder: MyRectSwiperPaginationBuilder(
                  color: col("6b6980"),
                  activeColor: Colors.white,
                  size: px(20),
                  activeSize: px(20),
                ),
              ),
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }
}

// 轮播矩形分页器
class MyRectSwiperPaginationBuilder extends SwiperPlugin {
  ///color when current index,if set null , will be Theme.of(context).primaryColor
  final Color activeColor;

  ///,if set null , will be Theme.of(context).scaffoldBackgroundColor
  final Color color;

  ///Size of the dot when activate
  final double activeSize;

  ///Size of the dot
  final double size;

  /// Space between dots
  final double space;

  final Key key;

  const MyRectSwiperPaginationBuilder(
      {this.activeColor,
      this.color,
      this.key,
      this.size: 10.0,
      this.activeSize: 10.0,
      this.space: 3.0});

  @override
  Widget build(BuildContext context, SwiperPluginConfig config) {
    if (config.itemCount > 20) {
      print(
          "The itemCount is too big, we suggest use FractionPaginationBuilder instead of DotSwiperPaginationBuilder in this sitituation");
    }
    Color activeColor = this.activeColor;
    Color color = this.color;

    if (activeColor == null || color == null) {
      ThemeData themeData = Theme.of(context);
      activeColor = this.activeColor ?? themeData.primaryColor;
      color = this.color ?? themeData.scaffoldBackgroundColor;
    }

    List<Widget> list = [];

    int itemCount = config.itemCount;
    int activeIndex = config.activeIndex;

    for (int i = 0; i < itemCount; ++i) {
      bool active = i == activeIndex;
      list.add(Container(
        key: Key("pagination_$i"),
        margin: EdgeInsets.all(space),
        child: Container(
          color: active ? activeColor : color,
          width: active ? activeSize : size,
          height: px(4),
        ),
      ));
    }

    if (config.scrollDirection == Axis.vertical) {
      return new Column(
        key: key,
        mainAxisSize: MainAxisSize.min,
        children: list,
      );
    } else {
      return new Row(
        key: key,
        mainAxisSize: MainAxisSize.min,
        children: list,
      );
    }
  }
}
